package com.iwuyc.tools.commons.structs.collections;

import com.iwuyc.tools.commons.util.collection.MapUtil;
import lombok.AccessLevel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Setter;

import java.io.Serializable;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * NavigateTreeNode
 *
 * @author Neil
 * @version 1.0.0
 * @since 2022.1
 */
@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class NavigateTreeNode<K extends Serializable, V extends Serializable> implements Serializable {
    private static final long serialVersionUID = 3631084533193623618L;
    /**
     * child nodes
     */
    private final Map<K, NavigateTreeNode<K, V>> children = new HashMap<>();
    private final K parentKey;
    /**
     * unique key
     */
    @EqualsAndHashCode.Include
    private final K primaryKey;
    /**
     * value,actually save data field
     */
    @Setter(AccessLevel.PACKAGE)
    private V val;
    /**
     * left score
     */
    private int left;
    /**
     * right score
     */
    private int right;

    private NavigateTreeNode(K parentKey, K primaryKey) {
        this.parentKey = parentKey;
        this.primaryKey = primaryKey;
    }

    /**
     * create node data
     *
     * @param parentKey  parent key the type same as primary key
     * @param primaryKey primary key of current node
     * @param <K>        Key type
     * @param <V>        value type
     * @return Navigate Tree Node instance
     */
    static <K extends Serializable, V extends Serializable> NavigateTreeNode<K, V> createNode(K parentKey, K primaryKey) {
        return new NavigateTreeNode<>(parentKey, primaryKey);
    }

    /**
     * add child node
     *
     * @param child child node
     */
    public void addChild(NavigateTreeNode<K, V> child) {
        this.children.put(child.getPrimaryKey(), child);
    }

    public boolean hasChildren() {
        return !MapUtil.isEmpty(this.children);
    }

    /**
     * 获取所有子节点，包含孙子节点的所有主键key，但不包含当前节点的主键
     * @return 所有子节点的主键
     */
    public Set<K> getAllChildrenPrimaryKey() {
        if (!hasChildren()) {
            return Collections.emptySet();
        }
        final Set<K> result = new HashSet<>();
        final Deque<NavigateTreeNode<K, V>> childNodes = new ArrayDeque<>(this.children.values());
        do {
            final NavigateTreeNode<K, V> child = childNodes.pop();
            result.add(child.getPrimaryKey());
            if (child.hasChildren()) {
                childNodes.addAll(child.children.values());
            }
        } while (!childNodes.isEmpty());
        return result;
    }
}
